<?php
/**
 * Created by Adu at 2020/4/10
 */

namespace backend\models\c2\form;


use common\models\c2\entity\ProductSku;
use common\models\c2\entity\ProductSkuAssemble;
use kzo\base\models\ModelTrait;
use Yii;
use yii\base\Model;
use yii\validators\RequiredValidator;

class SkuAssembleForm extends Model
{

    use ModelTrait;

    public $items;
    public $formView = '/assemble/_sku_assemble_form';
    /**
     * @var ProductSku
     */
    public $entityModel;

    public function rules()
    {
        return [
            [['items', 'created_at', 'updated_at'], 'safe'],
            [['items'], 'validateItems'],
        ]; // TODO: Change the autogenerated stub
    }

    public function validateItems($attribute)
    {
        $requiredValidator = new RequiredValidator();
        foreach ($this->$attribute as $index => $row) {
            $error = null;
            $requiredValidator->validate($row['product_id'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][product_id]';
                $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Product')]));
            }
            $requiredValidator->validate($row['num'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][num]';
                $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Number')]));
            }
        }
    }

    public function loadItems()
    {
        $this->items = $this->entityModel->getMaterialAssembles()->all();
    }

    public function loadDefaultValues($skipIfSet = true)
    {

    }

    public function save()
    {
        if (!empty($this->items)) {
            $sku_id = $this->entityModel->id;
            foreach ($this->items as $item) {
                $attributes = [
                    'product_id' => isset($item['product_id']) ? $item['product_id'] : 0,
                    'product_sku_id' => $sku_id,
                    'num' => isset($item['num']) ? $item['num'] : 0,
                    'position' => isset($item['position']) ? $item['position'] : 0,
                ];
                if (isset($item['id']) && $item['id'] == '') {
                    $itemModel = new ProductSkuAssemble();
                    $itemModel->setAttributes($attributes);
                    $itemModel->link('owner', $this->entityModel);
                } else {
                    $itemModel = ProductSkuAssemble::findOne($item['id']);
                    if (!is_null($itemModel)) {
                        $itemModel->updateAttributes($attributes);
                    }
                }
            }
        }
        return true;
    }

}